//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by QUAN on 15/11/17.
//  Copyright © 2015年 QUAN. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod: String {
    case POST = "POST"
    case GET = "GET"
}

private let  weiboDomain = "com.baidu.data.error"

class NetworkTools: AFHTTPSessionManager {
    //单例
    static let sharedTools: NetworkTools = {
       
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
 
    func requestJsonDict(method: HTTPMethod, urlString: String, parameters: [String : AnyObject]?, finised: (result: [String : AnyObject]?, error: NSError?) -> ()){
        
        //GET 请求
        if method == HTTPMethod.GET {
            
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                //正确回调
                if let dict = result as? [String : AnyObject] {
                    finised(result: dict, error: nil)
                    return
                }
                //数据格式错误
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据错误"])
                
                finised(result: nil, error: dataError)
                
                }, failure: { (_, error) -> Void in
              
                    finised(result: nil, error: error)
                    
                    print(error)
                    
            })
            
        } else {
            // POST 请求
            POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                
                if let dict = result as? [String : AnyObject] {
                    finised(result: dict, error: nil)
                    return
                }
                //数据格式不对
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据错误"])
                finised(result: nil, error: dataError)
                
                }, failure: { (_, error) -> Void in
                //错误回调
                finised(result: nil, error: error)
                    print(error)
            })
            
        }
        
        
        
    }
}



